package com.sina.shop.manage.dao.address;

import com.sina.shop.dao.ShopDataSourceDao;
import com.sina.shop.domain.address.Address;
import com.sina.shop.domain.address.Address_;
import com.sina.shop.domain.address.Status;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 段浩杰   2018-01-03-16:12
 */
@Repository("addressManageDao")
public class AddressManageDaoImpl extends ShopDataSourceDao implements AddressManageDao {

    @Override
    public Address getAddressByName(String name) {
        //暂时不提供
        return null;
    }

    @Override
    public int deleteAddress(Long id) {
        String hql = "delete from Address a where a.id = :id";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", id);

            return query.executeUpdate();
        });
    }

    @Override
    public int updateAddressStatus(Long aid) {
        String hql = "update Address a set a.status=:status where a.admin.id = :id and a.status = :statuss";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", aid);
            query.setParameter("status", Status.UN_USE);
            query.setParameter("statuss", Status.USE);
            return query.executeUpdate();
        });
    }

    @Override
    public List<Map<String, Object>> getAddressList(Address address) {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<Address> root = criteriaQuery.from(Address.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    addressSelection(root)
            );

            Predicate predicate = addressPredicate(address, builder, root);
            //指定查询条件
            criteriaQuery.where(predicate);
            //指定用于排序查询结果的排序表达式
            criteriaQuery.orderBy(
                    builder.asc(root.get(Address_.admin)),
                    builder.asc(root.get(Address_.status))
            );

            //创建查询
            Query<Tuple> query = session.createQuery(criteriaQuery);
            //得到起始条数
            int first = (address.getPage() - 1) * address.getRows();

            query.setFirstResult(first);
            query.setMaxResults(address.getRows());
            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }

    @Override
    public Long getAddressCount(Address address) {
        return template.executeWithNativeSession(session -> {

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
            Root<Address> root = criteriaQuery.from(Address.class);
            //根据id查找结果数
            criteriaQuery.select(
                    builder.count(root.get(Address_.id))
            );
            //组装查询条件
            criteriaQuery.where(
                    addressPredicate(address, builder, root)
            );
            //创建插叙语句
            Query<Long> query = session.createQuery(criteriaQuery);
            long count;
            try {
                //得到结果条数
                count = query.getSingleResult();
            } catch (NoResultException e) {
                count = 0;
            }
            return count;
        });
    }

    /**
     * 查询条件组装类
     *
     * @param address
     * @param builder
     * @param root
     * @return
     */
    protected Predicate addressPredicate(Address address, CriteriaBuilder builder
            , Root<Address> root) {
        List<Predicate> list = new ArrayList<>(4);

        if (address.getLastId() != null) {
            list.add(
                    builder.lt(root.get(Address_.id), address.getLastId())
            );
        }

        if (address.getAdmin() != null) {
            list.add(
                    builder.equal(root.get(Address_.admin), address.getAdmin().getId())
            );
        }

        if (address.getCreateStart() != null) {
            list.add(
                    builder.greaterThanOrEqualTo(root.get(Address_.createTime), address.getCreateStart())
            );
        }

        if (address.getCreateEnd() != null) {
            list.add(
                    builder.lessThanOrEqualTo(root.get(Address_.createTime), address.getCreateEnd())
            );
        }

        return builder.and(
                list.toArray(new Predicate[list.size()])
        );
    }


    /**
     * 所要查询的字段组装类
     *
     * @param root
     * @return
     */
    protected List<Selection<?>> addressSelection(Root<Address> root) {

        List<Selection<?>> list = new ArrayList<>(12);
        /**
         * 五条一组
         */
        list.add(root.get(Address_.id).as(Long.class).alias("id"));//id
        list.add(root.get(Address_.admin).alias("admin"));//
        list.add(root.get(Address_.province).alias("province"));
        list.add(root.get(Address_.city).alias("city"));
        list.add(root.get(Address_.country).alias("country"));

        list.add(root.get(Address_.street).alias("street"));//
        list.add(root.get(Address_.zipCode).alias("zipCode"));//
        list.add(root.get(Address_.createTime).alias("createTime"));
        list.add(root.get(Address_.status).alias("status"));

        return list;
    }


}
